package com.hspedu.hspspringmvc.context;

import com.hspedu.hspspringmvc.annotation.Controller;
import com.hspedu.hspspringmvc.servlet.HspDispatcherServlet;
import com.hspedu.hspspringmvc.xml.XMLParser;

import javax.jws.Oneway;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

//表示自己的容器
public class HspWebApplicationContext {
    private List<String> classFullPathList =new ArrayList<>();
    //定义属性ioc
    public ConcurrentHashMap<String, Object> ioc=new ConcurrentHashMap<>();
    public void init(){
        String basePackage = XMLParser.getBasePackage("hspspringmvc.xml");
        String[] basePackages = basePackage.split(",");
        if (basePackages.length>0){
            for (String s : basePackages) {
                scan(s);
            }
        }
        System.out.println("classFullPathList="+classFullPathList);
        executeInstance();
        System.out.println("扫描后的ioc容器="+ioc);
    }

    /**
     *扫描包得到全路径
     * @param pack 表示要扫描的包
     */
    public void scan(String pack){
        //得到包所在的工作路径 D:\javacode\loopy-springmvc\target\loopy-springmvc\WEB-INF\classes\com\hspedu\controller\
        URL url = this.getClass().getClassLoader().getResource("/" + pack.replaceAll("\\.", "/"));
        //System.out.println("url="+resource);
        String path = url.getFile();
        //System.out.println("path="+path);
        File file = new File(path);
        for(File file1:file.listFiles()){
            if(file1.isDirectory()){
                scan(pack+"."+file1.getName());
            }else {
               String classFullPath= pack+"."+ file1.getName().replaceAll(".class","");
               classFullPathList.add(classFullPath);
            }
        }
    }
    //将扫描的类在满足条件的情况下，反射到ioc容器
    public void executeInstance(){
        if (classFullPathList.size()==0){
            //说明没有扫描到
            return;
        }
        try {
            for (String classFullPath : classFullPathList) {
                Class<?> aClass = Class.forName(classFullPath);
                if (aClass.isAnnotationPresent(Controller.class)){
                   String beanName= aClass.getSimpleName().substring(0,1).toLowerCase()+
                           aClass.getSimpleName().substring(1);
                    ioc.put(beanName,aClass.newInstance());
                }//如果有其他可以扩展
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
